package com.example.r2dbcdemo.config.converter;

import com.example.r2dbcdemo.entity.TAuthor;
import com.example.r2dbcdemo.entity.TBookAuthor;
import io.r2dbc.spi.Row;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.convert.ReadingConverter;

import java.time.Instant;

@ReadingConverter //读取数据库数据的时候,把row转成 TBook
public class BookConverter implements Converter<Row, TBookAuthor> {

    @Override
    public TBookAuthor convert(Row source) {
        TBookAuthor tBookAuthor = new TBookAuthor();
        tBookAuthor.setId(source.get("id", Long.class));
        tBookAuthor.setTitle(source.get("title", String.class));
        Long authorId = source.get("author_id", Long.class);
        tBookAuthor.setAuthorId(authorId);
        tBookAuthor.setPublishTime(source.get("publish_time", Instant.class));

        //让 converter兼容更多的表结构处理
        if (source.getMetadata().contains("name")) {
            TAuthor tAuthor = new TAuthor();
            tAuthor.setId(authorId);
            tAuthor.setName(source.get("name", String.class));

            tBookAuthor.setAuthor(tAuthor);
        }

        return tBookAuthor;
    }
}
